package com.keya.features.tool;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang.StringUtils;
import org.dcm4che3.data.*;
import org.dcm4che3.io.DicomInputStream;
import org.dcm4che3.net.*;
import org.dcm4che3.net.pdu.AAssociateRQ;
import org.dcm4che3.net.pdu.ExtendedNegotiation;
import org.dcm4che3.net.pdu.PresentationContext;
import org.dcm4che3.tool.common.CLIUtils;
import org.dcm4che3.util.SafeClose;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * MoveSCU
 *
 * @author : xf.he
 * @version : 1.0 2023/11/2
 * @since : 1.0
 **/
@Slf4j
public class MoveSCU extends Device {

    private enum InformationModel {
        PatientRoot(UID.PatientRootQueryRetrieveInformationModelMove, "STUDY"),
        StudyRoot(UID.StudyRootQueryRetrieveInformationModelMove, "STUDY"),
        PatientStudyOnly(UID.PatientStudyOnlyQueryRetrieveInformationModelMove, "STUDY"),
        CompositeInstanceRoot(UID.CompositeInstanceRootRetrieveMove, "IMAGE"),
        HangingProtocol(UID.HangingProtocolInformationModelMove, null),
        ColorPalette(UID.ColorPaletteQueryRetrieveInformationModelMove, null);

        final String cuid;
        final String level;

        InformationModel(String cuid, String level) {
            this.cuid = cuid;
            this.level = level;
        }
    }

    private static final ResourceBundle rb = ResourceBundle.getBundle("dcm4che.movescu.messages");

    private static final int[] DEF_IN_FILTER = {
            Tag.SOPInstanceUID,
            Tag.StudyInstanceUID,
            Tag.SeriesInstanceUID
    };

    private final ApplicationEntity ae = new ApplicationEntity("MOVESCU");
    private final Connection conn = new Connection();
    private final Connection remote = new Connection();
    private final AAssociateRQ rq = new AAssociateRQ();
    private int priority;
    private String destination;
    private InformationModel model;
    private Attributes keys = new Attributes();
    private int[] inFilter = DEF_IN_FILTER;
    private Association as;
    private int cancelAfter;
    private boolean releaseEager;
    private ScheduledFuture<?> scheduledCancel;

    private final MoveResult moveResult = new MoveResult();

    public MoveSCU() {
        super("movescu");
        addConnection(conn);
        addApplicationEntity(ae);
        ae.addConnection(conn);
    }

    public final void setPriority(int priority) {
        this.priority = priority;
    }

    public void setCancelAfter(int cancelAfter) {
        this.cancelAfter = cancelAfter;
    }

    public void setReleaseEager(boolean releaseEager) {
        this.releaseEager = releaseEager;
    }

    public final void setInformationModel(InformationModel model, String[] tss,
                                          boolean relational) {
        this.model = model;
        if (rq.getPresentationContext(1) == null) {
            rq.addPresentationContext(new PresentationContext(1, model.cuid, tss));
        }
        if (relational)
            rq.addExtendedNegotiation(new ExtendedNegotiation(model.cuid, new byte[]{1}));
        if (model.level != null)
            addLevel(model.level);
    }

    public void addLevel(String s) {
        keys.setString(Tag.QueryRetrieveLevel, VR.CS, s);
    }

    public final void setDestination(String destination) {
        this.destination = destination;
    }

    public void addKey(int tag, String... ss) {
        VR vr = ElementDictionary.vrOf(tag, keys.getPrivateCreator(tag));
        keys.setString(tag, vr, ss);
    }

    public final void setInputFilter(int[] inFilter) {
        this.inFilter = inFilter;
    }

    private static CommandLine parseComandLine(String[] args) throws ParseException {
        Options opts = new Options();
        addServiceClassOptions(opts);
        addKeyOptions(opts);
        addRetrieveLevelOption(opts);
        addDestinationOption(opts);
        addCancelAfterOption(opts);
        addRetrieveEagerOption(opts);
        CLIUtils.addConnectOption(opts);
        CLIUtils.addBindOption(opts, "MOVESCU");
        CLIUtils.addAEOptions(opts);
        CLIUtils.addSendTimeoutOption(opts);
        CLIUtils.addRetrieveTimeoutOption(opts);
        CLIUtils.addPriorityOption(opts);
        CLIUtils.addCommonOptions(opts);
        return CLIUtils.parseComandLine(args, opts, rb, MoveSCU.class);
    }

    private static void addRetrieveLevelOption(Options opts) {
        opts.addOption(Option.builder("L")
                .hasArg()
                .argName("PATIENT|STUDY|SERIES|IMAGE|FRAME")
                .desc(rb.getString("level"))
                .build());
    }

    private static void addDestinationOption(Options opts) {
        opts.addOption(Option.builder()
                .longOpt("dest")
                .hasArg()
                .argName("aet")
                .desc(rb.getString("dest"))
                .build());

    }

    private static void addCancelAfterOption(Options opts) {
        opts.addOption(Option.builder()
                .hasArg()
                .argName("ms")
                .desc(rb.getString("cancel-after"))
                .longOpt("cancel-after")
                .build());
    }

    private static void addRetrieveEagerOption(Options opts) {
        opts.addOption(null, "release-eager", false, rb.getString("release-eager"));
    }

    private static void addKeyOptions(Options opts) {
        opts.addOption(Option.builder("m")
                .hasArgs()
                .argName("[seq.]attr=value")
                .desc(rb.getString("match"))
                .build());
        opts.addOption(Option.builder("i")
                .hasArgs()
                .argName("attr")
                .desc(rb.getString("in-attr"))
                .build());
    }

    private static void addServiceClassOptions(Options opts) {
        opts.addOption(Option.builder("M")
                .hasArg()
                .argName("name")
                .desc(rb.getString("model"))
                .build());
        CLIUtils.addTransferSyntaxOptions(opts);
        opts.addOption(null, "relational", false, rb.getString("relational"));
    }

    private void configureServiceClass(CommandLine cl) throws ParseException {
        setInformationModel(informationModelOf(cl), CLIUtils.transferSyntaxesOf(cl), cl.hasOption("relational"));
    }

    private static String destinationOf(CommandLine cl) throws ParseException {
        if (cl.hasOption("dest"))
            return cl.getOptionValue("dest");
        throw new ParseException(rb.getString("missing-dest"));
    }

    private void configureKeys(CommandLine cl) {
        CLIUtils.addAttributes(keys, cl.getOptionValues("m"));
        if (cl.hasOption("L"))
            addLevel(cl.getOptionValue("L"));
        if (cl.hasOption("i"))
            setInputFilter(CLIUtils.toTags(cl.getOptionValues("i")));
    }

    private static InformationModel informationModelOf(CommandLine cl) throws ParseException {
        try {
            return cl.hasOption("M")
                    ? InformationModel.valueOf(cl.getOptionValue("M"))
                    : InformationModel.StudyRoot;
        } catch (IllegalArgumentException e) {
            throw new ParseException(MessageFormat.format(
                    rb.getString("invalid-model-name"),
                    cl.getOptionValue("M")));
        }
    }

    public void open() throws IOException, InterruptedException, IncompatibleConnectionException, GeneralSecurityException {
        as = ae.connect(conn, remote, rq);
    }

    public void close() throws IOException, InterruptedException {
        if (scheduledCancel != null && releaseEager) { // release by scheduler thread
            return;
        }
        if (as != null && as.isReadyForDataTransfer()) {
            if (!releaseEager) {
                as.waitForOutstandingRSP();
            }
            as.release();
        }
    }

    public void retrieve(File f) throws IOException, InterruptedException {
        Attributes attrs = new Attributes();
        DicomInputStream dis = null;
        try {
            attrs.addSelected(new DicomInputStream(f).readDataset(), inFilter);
        } finally {
            SafeClose.close(dis);
        }
        attrs.addAll(keys);
        retrieve(attrs);
    }

    public void retrieve() throws IOException, InterruptedException {
        retrieve(keys);
    }

    private void retrieve(Attributes keys) throws IOException, InterruptedException {
        final DimseRSPHandler rspHandler = new DimseRSPHandler(as.nextMessageID()) {

            @Override
            public void onDimseRSP(Association as, Attributes cmd,
                                   Attributes data) {
                super.onDimseRSP(as, cmd, data);

                int status = cmd.getInt(Tag.Status, -1);
                moveResult.setStatus(status);
                int remaining = cmd.getInt(Tag.NumberOfRemainingSuboperations, moveResult.getNumberOfRemainingSuboperations());
                moveResult.setNumberOfRemainingSuboperations(remaining);
                int completed = cmd.getInt(Tag.NumberOfCompletedSuboperations, moveResult.getNumberOfCompletedSuboperations());
                moveResult.setNumberOfCompletedSuboperations(completed);
                int failed = cmd.getInt(Tag.NumberOfFailedSuboperations, moveResult.getNumberOfFailedSuboperations());
                moveResult.setNumberOfFailedSuboperations(failed);
                int warning = cmd.getInt(Tag.NumberOfWarningSuboperations, moveResult.getNumberOfWarningSuboperations());
                moveResult.setNumberOfWarningSuboperations(warning);
            }
        };

        as.cmove(model.cuid, priority, keys, null, destination, rspHandler);
        if (cancelAfter > 0) {
            scheduledCancel = schedule(() -> {
                        try {
                            rspHandler.cancel(as);
                            if (releaseEager) {
                                as.release();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    },
                    cancelAfter,
                    TimeUnit.MILLISECONDS);
        }
    }

    private static String[] initArgs(DicomNetParams netParas, String studyInstanceUID, String seriesInstanceUID) {
        List<String> list = new ArrayList<>();
        list.add("-c");
        list.add(netParas.getCalledAE() + "@" + netParas.getCalledIP() + ":" + netParas.getCalledPort());
        list.add("--dest");
        list.add(netParas.getCallingAE());
        list.add("-m");
        list.add("StudyInstanceUID" + "=" + studyInstanceUID);
        if (StringUtils.isNotEmpty(seriesInstanceUID)) {
            list.add("-m");
            list.add("SeriesInstanceUID" + "=" + seriesInstanceUID);
        }
        list.add("-M");
        list.add("StudyRoot");
        list.add("-L");
        list.add("SERIES");
        return list.toArray(new String[0]);
    }

    public MoveResult cMove(DicomNetParams dicomNetParams, String studyInstanceUID, String seriesInstanceUID) {
        try {
            setDeviceName(dicomNetParams.getCallingAE());
            ae.setAETitle(dicomNetParams.getCallingAE());
            CommandLine cl = parseComandLine(initArgs(dicomNetParams, studyInstanceUID, seriesInstanceUID));
            CLIUtils.configureConnect(remote, rq, cl);
            CLIUtils.configureBind(conn, ae, cl);
            CLIUtils.configure(conn, cl);
            remote.setTlsProtocols(conn.getTlsProtocols());
            remote.setTlsCipherSuites(conn.getTlsCipherSuites());
            configureServiceClass(cl);
            configureKeys(cl);
            setPriority(CLIUtils.priorityOf(cl));
            setDestination(destinationOf(cl));
            setCancelAfter(CLIUtils.getIntOption(cl, "cancel-after", 0));
            setReleaseEager(cl.hasOption("release-eager"));
            setExecutor(PacsExecutor.scheduledExecutorService);
            setScheduledExecutor(PacsExecutor.scheduledExecutorService);
            try {
                open();
                List<String> argList = cl.getArgList();
                if (argList.isEmpty())
                    retrieve();
                else
                    for (String arg : argList)
                        retrieve(new File(arg));
            } finally {
                close();
            }
        } catch (Exception e) {
            log.error(String.format("failed to move %s from %s@%s:%s caused by: %s", seriesInstanceUID,
                    dicomNetParams.getCalledAE(), dicomNetParams.getCalledIP(), dicomNetParams.getCalledPort(), e.getMessage()));
        }
        return moveResult;
    }
}
